package com.itrip.log.module.db.server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.itrip.log.core.BootstrapServer;
import com.itrip.log.module.collect.CollectModule;
import com.itrip.log.module.db.DaoTemplate;
import com.itrip.log.module.db.domain.HostBean;
import com.itrip.log.util.Util;

/**
 * Function:主机管理类<br>
 *
 * Date :2016年2月21日 <br>
 * Author :coder_czp@126.com<br>
 * Copyright (c) 2015,coder_czp@126.com All Rights Reserved.
 */
public class HostManager extends DaoTemplate {

	private List<HostBean> hosts = Collections.synchronizedList(new ArrayList<HostBean>());

	private CollectModule collectModule;

	public synchronized List<HostBean> getHosts() {
		if (hosts.isEmpty()) {
			hosts.addAll(this.<HostBean>selectList("HostBean.getListByMapWithPwd", null));
		}
		return hosts;
	}

	@Override
	public int delete(String namespace, long id) {
		int delete = super.delete(namespace, id);
		for (HostBean tmp : hosts) {
			if (tmp.getId() == id) {
				collectModule.stopCollect(tmp);
				hosts.remove(tmp);
				break;
			}
		}
		return delete;
	}

	@Override
	public Object save(String namespace, Object obj) {
		HostBean bean = (HostBean) obj;
		bean.setPwd(Util.encrypt(bean.getPwd()));
		HostBean save = (HostBean) super.save(namespace, obj);
		collectModule.startCollect(save);
		return save;
	}

	@Override
	public int update(String namespace, Object obj) {
		HostBean bean = (HostBean) obj;
		bean.setPwd(Util.encrypt(bean.getPwd()));
		int update = super.update(namespace, obj);
		collectModule.reConnectHost(bean);
		return update;
	}

	@Override
	public String processClassName() {
		return HostBean.class.getName();
	}

	@Override
	public void setBoostServer(BootstrapServer server) {
		collectModule = server.getModule(CollectModule.class);
	}

}
